package com.powroznik.tracker.engine.services;

import java.util.List;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import com.powroznik.tracker.engine.data.Device;
import com.powroznik.tracker.engine.data.DeviceConfiguration;
import com.powroznik.tracker.engine.data.Location;
import com.powroznik.tracker.engine.data.TrackerEngineDao;

@Path("/deviceService")
public class DeviceService {
	private TrackerEngineDao trackerEngineDao;

	private ValidationService validationService;

	@WebMethod
	@POST
	@Path("/getDeviceConfiguration")
	@Produces("application/json")
	public DeviceConfiguration getDeviceConfiguration(
			@WebParam(name = "device") @FormParam("device") Device device) {
		assert validationService.isGenuine(device, false);
		device = trackerEngineDao.getDeviceById(device.getId());
		return device.getDeviceConfiguration();
	}

	@WebMethod
	@GET
	@Path("/ping")
	@Produces("text/plain")
	public String ping(
			@WebParam(name = "message") @QueryParam("message") String message) {
		assert validationService.isGenuine(message);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < message.length(); i++) {
			sb.insert(0, message.charAt(i));
		}
		return sb.toString();
	}

	@WebMethod
	@GET
	@Path("/registerNewDevice")
	@Produces("application/json")
	public Device registerNewDevice() {
		Device device = new Device();
		{
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < 8; i++) {
				int j = (int) (Math.random() * 36);
				if (j < 10) {
					sb.append((char) ('0' + j));
				} else {
					sb.append((char) ('A' + j - 10));
				}
			}
			device.setCode1(sb.toString());
		}
		{
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < 8; i++) {
				int j = (int) (Math.random() * 36);
				if (j < 10) {
					sb.append((char) ('0' + j));
				} else {
					sb.append((char) ('A' + j - 10));
				}
			}
			device.setCode2(sb.toString());
		}
		trackerEngineDao.save(device);
		return device;
	}

	@WebMethod
	@POST
	@Path("/saveLocations")
	public void saveLocations(
			@WebParam(name = "device") @FormParam("device") Device device,
			@WebParam(name = "locations") @FormParam("locations") List<Location> locations) {
		assert validationService.isGenuine(device, false);
		assert validationService.isGenuine(locations, true);
		for (Location location : locations) {
			location.setDevice(device);
			trackerEngineDao.save(location);
		}
	}

	public void setTrackerEngineDao(TrackerEngineDao trackerEngineDao) {
		this.trackerEngineDao = trackerEngineDao;
	}

	public void setValidationService(ValidationService validationService) {
		this.validationService = validationService;
	}
}
